import pandas as pd
import matplotlib.pyplot as plt
import ipywidgets as widgets
import plotly.express as px
from IPython.display import display
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import plotly.io as pio
# Load the data
data = pd.read_csv('filtered_US_aidpk.csv')
# Display the first few rows
data.head()
| Fiscal Year | US Category Name | US Sector Name | Current Dollar Amount | Activity Name | Implementing Partner Category Name | Implementing Partner Sub-category ID | Implementing Partner Name | |
|---|---|---|---|---|---|---|---|---|
| 0 | 2023 | Humanitarian Assistance | Protection, Assistance and Solutions | 25076538 | Emergency Food Assistance | Multilateral | Multilateral - United Nations | World Food Program |
| 1 | 2023 | Economic Development | Agriculture | 8000000 | Emergency food assistance | Multilateral | Multilateral - United Nations | Food and Agriculture Organisation |
| 2 | 2023 | Health | Pandemic Influenza and Other Emerging Threats ... | 6100451 | Integrated Health Systems Strengthening and Se... | NGO | NGO - United States | John Snow International |
| 3 | 2023 | Humanitarian Assistance | Protection, Assistance and Solutions | 5157625 | Humanitarian Assistance - provide rapid respon... | NGO | NGO - United States | NGO - United States Redacted |
| 4 | 2023 | Program Support | Direct Administrative Costs | 4044723 | USAID Pay and Benefits | Government | Government - United States | U.S. Government - U.S. Agency for Internationa... |
# Create a sorted list of years
years = sorted(data['Fiscal Year'].unique())
# Create a dropdown widget
year_widget = widgets.Dropdown(
options=years,
value=years[0],
description='Year:',
disabled=False,
)
# Function to update the chart
def update_chart(year):
# Filter data for selected year
data_year = data[data['Fiscal Year'] == year]
# Group by category and sum dollar amounts
category_sums = data_year.groupby('US Category Name')['Current Dollar Amount'].sum()
# Create bar chart
plt.figure(figsize=(10, 6))
plt.bar(category_sums.index, category_sums.values)
plt.xlabel('Category')
plt.ylabel('Total Dollar Amount')
plt.title(f'Total Aid Amount by Category in {year}')
plt.xticks(rotation=90)
plt.show()
# Display the widget and chart
display(year_widget)
_ = widgets.interact(update_chart, year=year_widget)
Dropdown(description='Year:', options=(2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012,…
interactive(children=(Dropdown(description='Year:', options=(2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2…
# Total aid given each year
fig1 = px.bar(data, x='Fiscal Year', y='Current Dollar Amount',
hover_data=['US Category Name'], # Add this line
labels={'Current Dollar Amount':'Dollar Amount (in billions $)',
'Fiscal Year': 'Year' , 'US Category Name': 'Ca'},
title='Total US Aid Given Each Year 2000-2023',
template='plotly_white')
fig1.update_traces(marker_color='skyblue')
fig1.update_layout(yaxis_tickprefix = '$', yaxis_ticksuffix = 'B')
fig1.show()
# Distribution of aid among different categories
data_category = data.groupby('US Category Name')['Current Dollar Amount'].sum().reset_index()
fig2 = px.pie(data_category, names='US Category Name', values='Current Dollar Amount',
labels={'US Category Name': 'Category'},
title='Distribution of Aid Among Categories',
template='plotly_white')
fig2.show()
# Top 10 sectors receiving aid
data_sector = data.groupby('US Sector Name')['Current Dollar Amount'].sum().nlargest(10).reset_index()
fig3 = px.bar(data_sector, y='US Sector Name', x='Current Dollar Amount',
labels={'Current Dollar Amount':'Total Dollar Amount (in billions)',
'US Sector Name': 'Sector'},
title='Top 10 Sectors Receiving Aid',
template='plotly_white', orientation='h')
fig3.update_traces(marker_color='skyblue')
fig3.update_layout(xaxis_tickprefix = '$', xaxis_ticksuffix = 'B')
fig3.show()
# Group the data by year and category, then reset the index
data_grouped = data.groupby(['Fiscal Year', 'US Category Name'])['Current Dollar Amount'].sum().reset_index()
# Create a list of unique years
years = data_grouped['Fiscal Year'].unique()
# Create a figure
fig4 = go.Figure()
# Add one trace for each year
for year in years:
fig4.add_trace(
go.Pie(
labels=data_grouped[data_grouped['Fiscal Year'] == year]['US Category Name'],
values=data_grouped[data_grouped['Fiscal Year'] == year]['Current Dollar Amount'] / 1e6, # Convert to billions
name=str(year),
visible=False if year != min(years) else True, # Only the first year is visible initially
hoverinfo='label+value+percent',
textinfo='label+value',
texttemplate='%{label}<br>$%{value:.2f}mn',
hole=0.7
)
)
# Add a dropdown menu to select the year
buttons = []
for i, year in enumerate(years):
visibility = [False] * len(years)
visibility[i] = True
button = dict(
label = str(year),
method = 'update',
args = [{'visible': visibility}]
)
buttons.append(button)
fig4.update_layout(
margin=dict(
t=130, # top margin
pad=100 # padding
),
updatemenus=[
dict(
type="dropdown",
direction="down",
buttons=buttons,
showactive=True,
xanchor="right",
yanchor="bottom",
)
],
title='US AID to Pakistan -Distribution of Aid Among Categories 2001-2023',
template='plotly_white'
)
fig4.show()
from IPython.display import display, clear_output
# Create a year slider
year_slider = widgets.IntSlider(min=data['Fiscal Year'].min(), max=data['Fiscal Year'].max(), step=1, description='Year')
# Create output widgets for the figures
output_fig1 = widgets.Output()
output_fig2 = widgets.Output()
output_fig3 = widgets.Output()
output_fig4 = widgets.Output()
def display_figures(year):
with output_fig1:
clear_output(wait=True) # Clear previous figure
fig1.show()
with output_fig2:
clear_output(wait=True) # Clear previous figure
fig2.show()
with output_fig3:
clear_output(wait=True) # Clear previous figure
fig3.show()
with output_fig4:
clear_output(wait=True) # Clear previous figure
# Filter data for the selected year
data_year = data[data['Fiscal Year'] == year]
# Group the data by category, then reset the index
data_grouped = data_year.groupby('US Category Name')['Current Dollar Amount'].sum().reset_index()
# Create the pie chart
fig = go.Figure(
data=[go.Pie(
labels=data_grouped['US Category Name'],
values=data_grouped['Current Dollar Amount'] / 1e6, # Convert to millions
hoverinfo='label+value+percent',
textinfo='label+value',
texttemplate='%{label}<br>$%{value:.2f}B',
hole=0.7
)]
)
fig.update_layout(
title='US Aid to Pakistan - Distribution of Aid Among Categories in {}'.format(year),
template='plotly_white'
)
fig.show()
# Call the function with the minimum year to display the figures initially
display_figures(data['Fiscal Year'].min())
# Create a widget container to display the slider and the figures
widget_container = widgets.VBox([year_slider, output_fig1, output_fig2, output_fig3, output_fig4])
# Display the widget container
display(widget_container)
# Connect the slider to the function
year_slider.observe(lambda change: display_figures(change.new), 'value')
VBox(children=(IntSlider(value=2001, description='Year', max=2023, min=2001), Output(), Output(), Output(), Ou…